package com.thb.pay.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.thb.pay.api.sys.SysPermissionServiceApi;
import com.thb.pay.api.sys.vo.req.SysRolePermissionReq;
import com.thb.pay.api.sys.vo.req.SysUserPermissionReq;
import com.thb.pay.api.sys.vo.resp.SysPermissionVo;
import com.thb.pay.system.entity.SysRoleResource;
import com.thb.pay.system.service.SysRoleResourceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 系统-授权表 前端控制器
 * </p>
 *
 * @author lucky
 * @since 2019-07-21
 */
@RestController
public class SysPermissionController implements SysPermissionServiceApi {

    @Autowired
    private SysRoleResourceService sysRoleResourceService;


    @Override
    public List<SysPermissionVo> findPermissionListByRoleId(@RequestParam("roleId") Long roleId) {
        List<SysPermissionVo> permissionVoList = Lists.newArrayList();
        LambdaQueryWrapper<SysRoleResource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleResource::getRoleId, roleId);
        List<SysRoleResource> permissionList = sysRoleResourceService.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(permissionList)) {
            permissionList.forEach(sysPermission -> {
                SysPermissionVo permissionVo = new SysPermissionVo();
                BeanUtils.copyProperties(sysPermission, permissionVo);
                permissionVoList.add(permissionVo);
            });
        }
        return permissionVoList;
    }

    @Override
    public void saveRolePermissions(@RequestBody SysRolePermissionReq rolePermissionReq) {
        LambdaQueryWrapper<SysRoleResource> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleResource::getRoleId, rolePermissionReq.getRoleId());
        sysRoleResourceService.delete(queryWrapper);
        rolePermissionReq.getResourceIds().forEach(resourceId -> {
            SysRoleResource permission = new SysRoleResource();
            permission.setRoleId(rolePermissionReq.getRoleId());
            permission.setResourceId(resourceId);
            sysRoleResourceService.insert(permission);
        });
    }

    @Override
    public void saveUserPermissions(SysUserPermissionReq userPermissionReq) {

    }
}
